use std::sync::Arc;
use anyhow::Context;
use tokio::net::TcpStream;
use mcp_sdk::{
    client::McpClient, transport::tcp::TcpTransport, 
    McpClientCapabilities, McpImplementation, McpToolCall, McpToolCallResultContent
};
use tokio;
use log::{info, LevelFilter};
use simple_logger::SimpleLogger;

async fn result_main() -> anyhow::Result<()> {
    SimpleLogger::new().with_level(LevelFilter::Info).init().context("Init logger")?;

    let stream = TcpStream::connect("127.0.0.1:020716").await?;
    let (transport, _sender) = TcpTransport::new(stream).await;

    let client = McpClient::new(Arc::new(transport));
 
    let implementation = McpImplementation {
        name: "Client".to_string(),
        version: "3.12.3".to_string(),
    };
    let capabilities = McpClientCapabilities::default();

    info!("Initializing MCP client...");
    let server_capabilities = client.initialize(implementation, capabilities).await?;
    info!("Server capabilities: {:?}", server_capabilities);

    info!("Sending test tools/list...");
    let tools = client.tools_list().await?;
    for tool in tools {
        info!("{:?}", tool);
    }

    info!("Call a tool!");
    let tool_call = McpToolCall {
        name: "get_my_name".to_string(),
        arguments: None,   
    };
    let result = client.tools_call(tool_call).await?;
    info!("Get result: '{:?}'", result.content[0]);

    info!("Shutting down...");
    client.shutdown().await?;

    Ok(())
}

#[tokio::main]
async fn main() {
    if let Err(err) = result_main().await {
        eprintln!("{}", err);
    }
}